【LeetCode-面试算法经典-Java实现】【121-Best Time to Buy and Sell Stock(最佳买卖股票的时间)】

126 篇文章 82 订阅

【121-Best Time to Buy and Sell Stock(最佳买卖股票的时间)】


【LeetCode-面试算法经典-Java实现】【所有题目目录索引】

原题

  Say you have an array for which the ith element is the price of a given stock on day i.
  If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

题目大意

  给一个数组prices[],prices[i]代表股票在第i天的售价,求出只做一次交易(一次买入和卖出)能得到的最大收益。

解题思路

  只需要找出最大的差值即可,即 max(prices[j] – prices[i]) ,i < j。一次遍历即可,在遍历的时间用遍历low记录 prices[o….i] 中的最小值,就是当前为止的最低售价,时间复杂度为 O(n)。

代码实现

算法实现类

public class Solution {

    public int maxProfit(int[] prices) {

        if (prices == null || prices.length < 1) {
            return 0;
        }

        int min = prices[0];
        int profit = 0;

        // 第i天的价格可以看作是买入价也可以看作是卖出价
        for (int i = 1; i < prices.length; i++) {
            // 找到更低的买入价
            if (min > prices[i]) {
                // 更新买入价
                min = prices[i];
            } 
            // 当天的价格不低于买入价
            else {
                // 如果当天买出的价格比之前卖出的价格高
                if (profit < prices[i] - min) {
                    // 更新卖出价
                    profit = prices[i] - min;
                } 
            }
        }

        return profit;
    }
}

评测结果

  点击图片,鼠标不释放,拖动一段位置,释放后在新的窗口中查看完整图片。

这里写图片描述

特别说明

欢迎转载,转载请注明出处【http://blog.csdn.net/derrantcm/article/details/47651235

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值